﻿using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace CWM.Skinn
{
    public static partial class SkinnContextCommands
    {
        [CtxMenuItem("Transform/Select/Mesh Filters",
            "Select all child gameObjects with MeshFilters.",
            ContextRequirements.Children, 0)]
        public static void TransformSelectMR()
        {
            var renders = new List<GameObject>();
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Transform>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                var t = context.transform.GetAllChildren(true).ToArray();

                for (int i = 0; i < t.Length; i++)
                    if (t[i].GetComponent<MeshFilter>() && !renders.Contains(t[i].gameObject)) renders.Add(t[i].gameObject);
            }
            Selection.objects = renders.ToArray();
            SkinnContext.Finished();

        }

        [CtxMenuItem("Transform/Select/Skinned Meshes",
            "Select all child gameObjects with SkinnedMeshRenderers.",
            ContextRequirements.Children, 0)]
        public static void TransformSelectSMR()
        {
            var renders = new List<GameObject>();
            foreach (var item in SkinnContext.GetContextItems())
            {
                var context = item.GetComponent<Transform>();
                if (SkinnEx.IsNullOrNotInAScene(context)) continue;
                var t = context.transform.GetAllChildren(true).ToArray();

                for (int i = 0; i < t.Length; i++)
                    if (t[i].GetComponent<SkinnedMeshRenderer>() && !renders.Contains(t[i].gameObject)) renders.Add(t[i].gameObject);
            }
            Selection.objects = renders.ToArray();
            SkinnContext.Finished();

        }

        [CtxMenuItem("Transform/Select/Missing Components",
            "Select all gameObject with missing components.",
            ContextRequirements.Children, 0)] //http://wiki.unity3d.com/index.php?title=FindMissingScripts
        public static void TransformSelectMissing()
        {
            GameObject[] all = Resources.FindObjectsOfTypeAll<GameObject>();
            List<GameObject> selection = new List<GameObject>();
            foreach (GameObject item in all)
            {
                Component[] components = item.GetComponents<Component>();
                for (int i = 0; i < components.Length; i++) if (components[i] == null) selection.Add(item);
            }
            if (selection.Count > 0) Selection.objects = selection.ToArray();
            else SkinnContext.LogWarning("no missing components found");
            SkinnContext.Finished();
        }
    }
}
